<template>
  <el-container class="pure pure-ticket">
    <el-header class="header">
      <el-row type="flex" justify="space-between" class="service-desk">
        <el-col :span="12" class="base-margin-left">
          <span class="agent">当前坐席类型：<span class="agent-value">人工坐席；</span></span>
          <span class="agent">坐席人员:<span class="agent-value">谢波；</span></span>
          <pure-button label="坐席设定" icon="earphone" />
        </el-col>
        <el-col class="service-detail">
          <span>
            服务台情况
            <el-tooltip placement="top">
              <div slot="content">

                统计数据与查询条件(时间、坐席人员)有关联
                <br>
                默认查询今日所有坐席人员的情况
              </div>
              <svg-icon icon-class="question" />
            </el-tooltip>
            ：
          </span>
          <span class="item">已接：<span>{{ redData.pickedUp }}</span></span>
          <span class="item">未接：<span>{{ redData.missed }}</span></span>
          <span class="item">已建：<span>{{ redData.createOrder }}</span></span>
          <span class="item">电话解决：<span>{{ redData.endPhone }}</span></span>
        </el-col>
      </el-row>

    </el-header>
    <el-main>
      <pure-table
        ref="pureTable"
        :columns="filteredColumns"
        :query-condition="queryCondition"
        :list-api="listApi"
        :operation-column-width="250"
      >
        <template slot="header">

          <flow-chart-panel
            :default-template-type="queryCondition.temp"
            :red-data="redData"
            @transition-end="onFlowChartPanelTransitionEnd"
            @templateTypeChange="onTemplateTypeChange"
          />
          <el-row type="flex" class="base-margin-top">
            <el-col :span="22">
              <template
                v-if="tableColumnType==='ticket'"
              >
                <el-input
                  v-model="queryConditionTemp.ticketQuery"
                  class="item"
                  placeholder="故障描述/工单号/报修电话"
                >
                  <i slot="prefix" class="el-icon-search el-input__icon" />
                </el-input>
                <el-date-picker
                  v-model="queryConditionTemp.ticketCreateInfoDate"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="报修时间"
                  end-placeholder="报修时间"
                  size="mini"
                  class="item"
                />
                <user-select v-model="queryConditionTemp.createUserList" placeholder="建单人" multiple collapse-tags size="mini" class="item" />
                <dept-multi-cascader v-model="queryConditionTemp.ticketHospitalList" :show-all-levels="false" placeholder="报修院区/科室" class="item" />
                <dic-select v-model="queryConditionTemp.degree" dic-key="obs_fault_degree" placeholder="紧急程度" size="mini" class="item" />
                <dic-select v-show="queryConditionExpand" v-model="queryConditionTemp.rangeType" dic-key="obs_fault_range" placeholder="影响范围" size="mini" class="item" />
                <dic-select v-show="queryConditionExpand" v-model="queryConditionTemp.source" dic-key="obs_fault_source" placeholder="故障来源" size="mini" class="item" />
                <dic-select v-show="queryConditionExpand" v-model="queryConditionTemp.orderState" dic-key="obs_fault_state" placeholder="工单状态" size="mini" class="item" />
                <user-select v-show="queryConditionExpand" v-model="queryConditionTemp.makeUserList" placeholder="处理人" multiple collapse-tags size="mini" class="item" />
                <user-select v-show="queryConditionExpand" v-model="queryConditionTemp.serverUserList" placeholder="坐席人" multiple collapse-tags size="mini" class="item" />
                <pure-button label="查询" size="mini" icon="search" type="minor" @click="onQueryTicket" />
                <pure-button label="重置" size="mini" icon="reset" type="patch" @click="onResetTicket" />
                <pure-button :label="expandLabel" size="mini" type="text" :icon="expandIcon" icon-position="right" @click="onToggleQueryCondition" />
              </template>
              <template
                v-if="tableColumnType==='callRecord'"
              >
                <el-input
                  v-model="queryConditionTemp.recordQuery"
                  class="item"
                  placeholder="工单号/报修电话"
                >
                  <i slot="prefix" class="el-icon-search el-input__icon" />
                </el-input>
                <el-date-picker
                  v-model="queryConditionTemp.createInfoDate"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="来电时间"
                  end-placeholder="来电时间 "
                  size="mini"
                  class="item"
                />
                <dic-select v-model="queryConditionTemp.dealType" dic-key="obs_deal_type" placeholder="处置类型" size="mini" class="item" />
                <dept-multi-cascader v-model="queryConditionTemp.hospitalList" placeholder="报修院区/科室" class="item" />
                <user-select v-model="queryConditionTemp.userList" placeholder="坐席人/所找人员" multiple collapse-tags size="mini" class="item" />
                <pure-button label="查询" size="mini" icon="search" type="minor" @click="onQueryRecord" />
                <pure-button label="重置" size="mini" icon="reset" type="patch" @click="onResetRecord" />
              </template>
            </el-col>
            <el-col :span="2" class="text-align-end">
              <pure-button label="创建工单" icon="add" @click="onCreateTicket()" />
            </el-col>
          </el-row>
        </template>
        <template slot="indexColumn">
          序号
        </template>
        <template slot="columns" slot-scope="{row,prop}">
          <div v-if="prop==='recording'">
            <pure-audio
              v-if="row.recording"
              :key="row.recording"
              :the-url="row.recording"
            />
            <span v-else>-</span>
          </div>
          <span v-else-if="prop === 'callTypeToName'" :class="['call-record-status--'+row.callType,'prefix-dot']">{{ row[prop] }}</span>
          <span v-else-if="prop ==='source'">
            {{ row[prop] }}
          </span>
          <span v-else-if="prop ==='degreeToName'" :class="['degree','degree--'+row.degree]">
            {{ row[prop] }}
          </span>
          <span v-else-if="prop ==='rangeType'">
            {{ row[prop] }}
          </span>
          <span v-else-if="prop ==='currStateToName'" :class="['state--'+row.currState,'state','prefix-dot']">{{ row[prop] }}</span>
          <span v-else-if="prop==='faultRemark'" class="fault-description" @click="onViewTicket(row.orderNum)">
            <pure-tag
              v-if="row['orderNum'].includes('#')"
              label="协"
              type="danger"
              @click="onViewTicket(row.parentOrderNum)"
            />

            <pure-tag
              v-if="row.hurryCount"
              :label="row.hurryCount"
              icon="clock"
              type="warning"
              :max="99"
            />
            <pure-tag
              v-if="row.repeatCount"
              :label="row.repeatCount"
              icon="loop"
              :max="99"
            />
            {{ row[prop] }}
          </span>
          <span v-else-if="prop==='linkedCode'">
            <span v-if="row[prop]" class="ticket-id" @click="onViewTicket(row[prop])">
              {{ row[prop] }}
            </span>
            <span v-else>
              -
            </span>
          </span>
          <span v-else-if="prop==='dealTypeToName'">
            {{ row[prop] || '未处理' }}
          </span>
          <span v-else>
            {{ row[prop] }}
          </span>
        </template>
        <template v-if="tableColumnType!=='callRecordPhoneFind'" :slot="tableColumnType==='callRecordPhoneFind'?'':'operationColumn'" slot-scope="{row}">
          <template v-if="tableColumnType === 'callRecord'">
            <pure-more-button :slice-number="3 ">
              <pure-button
                v-if="row.callType===0&&!row.dealType"
                type="text"
                label="建单"
                @click="onCreateTicket('byCallRecord',row)"
              />
              <pure-button
                v-if="row.type===0&&!row.dealType"
                type="text"
                label="电话找人"
                @click="onFindPerson(row.id)"
              />
              <pure-button
                v-if="!row.dealType"
                type="text"
                label="无效电话"
                @click="onInvalidPhone(row.id)"
              />
              <pure-button
                v-if="['end_phone','create_order'].includes(row.dealType)"
                type="text"
                label="查看"
                @click="onViewTicket(row.orderNum)"
              />
            </pure-more-button>
          </template>

          <template v-else>
            <pure-more-button :slice-number="3">
              <pure-button
                v-if="canDispatchState.includes(row['currState'])"
                type="text"
                label="派单"
                @click="onDispatchTicket(row.orderNum)"
              />
              <pure-button
                v-if="row.currState === 'wait_accept'"
                type="text"
                label="重派"
                @click="onReDispatchTicket(row.orderNum)"
              />
              <pure-button
                v-if="canEndState.includes(row['currState'])"
                type="text"
                label="终止"
                text-color="warning"
                @click="onUpdateTicket(row.orderNum, 'endTermination')"
              />

              <pure-button
                v-if="
                  canSuspendState.includes(
                    row['currState']
                  )
                "
                type="text"
                label="暂停"
                text-color="warning"
                @click="onUpdateTicket(row.orderNum, 'suspend')"
              />

              <pure-button
                v-if="canOpenState.includes(row['currState'])"
                type="text"
                label="开启"
                @click="onOpenSuspendedTicket(row.orderNum)"
              />

              <pure-button
                v-if="canRestartState.includes(row['currState'])"
                type="text"
                label="重启"
                @click="onRestartTerminatedTicket(row.orderNum)"
              />
              <pure-button
                type="text"
                label="查看"
                @click="onViewTicket(row.orderNum)"
              />
              <pure-button
                v-if="canUpdateAnswerAndFaultInfoState.includes(row['currState'])"
                type="text"
                label="编辑"
                @click="onUpdateAnswerAndFaultInfo(row.orderNum)"
              />

              <pure-button
                type="text"
                label="打印"
                @click="onPrintTicket(row.id)"
              />
            </pure-more-button>
          </template>
        </template>
      </pure-table>
    </el-main>
  </el-container>
</template>

<script>
import TicketMixin from '../mixin';
import ServiceDeskApi from './api';
import FlowChartPanel from './components/test.vue';
import PureWebsocket from '@/common/utils/pureWebSocket';
import PureAudio from '@/common/components/audio';
import Moment from 'moment';
import DicSelect from '@/features/system/dataDictionary/components/dicSelect.vue';
import UserSelect from '@/features/system/user/components/userSelect.vue';
import DeptMultiCascader from '@/features/system/departmentManagement/components/deptMultiCascader.vue';
export default {
  name: 'TicketServiceDesk',
  components: {
    FlowChartPanel,
    PureAudio,
    DicSelect,
    UserSelect,
    DeptMultiCascader,
  },
  mixins: [
    TicketMixin,
  ],
  data() {
    return {
      columns: [],
      // tableColumnType: 'callRecord',
      tableColumnType: 'ticket',
      // listApi: ServiceDeskApi.callRecordList,
      listApi: ServiceDeskApi.list,
      flowChartVisible: true,
      redData: {},
      queryCondition: {
        temp: 'UNTENITED',
        keyword: null,
        createInfoEndDate: null,
        createInfoStartDate: null,
        dealType: null,
        hospitalList: [],
        userList: [],
        createUserList: [],
        degree: null,
        rangeType: null,
        source: null,
        orderState: null,
        makeUserList: [],
        serverUserList: [],
      },
      queryConditionTemp: {
        keyword: '',

        createFaultTime: [],
        createUserList: [],

        /**
         * 通话查询参数
         */
        recordQuery: null,
        createInfoDate: [],
        dealType: null,
        hospitalList: [],
        userList: [],
        /**
         * 工单查询参数
         */
        ticketQuery: null,
        ticketCreateInfoDate: [],
        degree: null,
        rangeType: null,
        source: null,
        orderState: null,
        makeUserList: [],
        serverUserList: [],
        ticketHospitalList: [
        ],
      },
      tempQueryCondition: {},
      canDispatchState: [
        'wait_delivery',
      ],
      canEndState: [
        'processing',
        'suspended',
        'wait_delivery',
        'wait_accept',
      ],
      canSuspendState: [
        'processing',
      ],
      canRestartState: [
        'terminated',
      ],
      canOpenState: [
        'suspended',
      ],
      canUpdateAnswerAndFaultInfoState: [
        'wait_delivery',
        'wait_accept',
        'processing',
      ],
      seatType: '',
      todayDate: Moment().format('YYYY-MM-DD'),
      autoRefreshTimer: null,
      autoRefreshTimeInterval: 60 * 1000,
      callDivertLabel: '',
      engineersNeedToNotify: '',
      queryConditionExpand: true,
    };
  },
  computed: {
    expandLabel() {
      if (this.queryConditionExpand) {
        return '收起';
      } else {
        return '展开';
      }
    },
    expandIcon() {
      if (this.queryConditionExpand) {
        return 'arrow-up';
      } else {
        return 'arrow-down';
      }
    },
    filteredColumns() {
      return this.columns.filter(item => item.checked).map(item => {
        return item;
      });
    },
    callRecordTableColumn() {
      return [{
        name: '接听情况',
        label: '接听情况',
        prop: 'callTypeToName',
        id: 1,
        order: 1,
        checked: true,
        width: 86,
      },
      {
        name: '报修电话',
        label: '报修电话',
        prop: 'phone',
        id: 2,
        order: 2,
        checked: true,
        width: 146,
      },
      {
        name: '报修院区/科室',
        label: '报修院区/科室',
        prop: 'deptName',
        id: 3,
        order: 3,
        checked: true,
        width: 158,
      },
      {
        name: '处置类型',
        label: '处置类型',
        prop: 'dealTypeToName',
        id: 4,
        order: 4,
        checked: true,
        width: 103,
      },
      {
        name: '来电时间',
        label: '来电时间',
        prop: 'createTime',
        id: 5,
        order: 5,
        checked: true,
        width: 211,
      },
      {
        name: '(关联)工单号',
        label: '(关联)工单号',
        prop: 'linkedCode',
        id: 6,
        order: 6,
        checked: true,
        width: 230,
        fixed: 'left',
      },
      {
        name: '坐席人',
        label: '坐席人',
        prop: 'receptionName',
        id: 7,
        order: 7,
        checked: true,
        width: 103,
      },
      {
        name: '所找人员',
        label: '所找人员',
        prop: 'findUserName',
        id: 8,
        order: 8,
        checked: true,
        width: 103,
      },
      {
        name: '录音',
        label: '录音',
        prop: 'recording',
        id: 9,
        order: 9,
        checked: true,
        width: 288,
      },
      ];
    },
    callRecordPhoneFindTableColumn() {
      return [
        {
          name: '类型',
          label: '类型',
          prop: 'type',
          id: 1,
          order: 1,
          checked: true,
          width: 102,
        }, {
          name: '通话时间',
          label: '通话时间',
          prop: 'createTime',
          id: 2,
          order: 2,
          checked: true,
          width: 227,
        }, {
          name: '报修科室',
          label: '报修科室',
          prop: 'deptName',
          id: 3,
          order: 3,
          checked: true,
          width: 420,
        },
        {
          name: '报修人',
          label: '报修人',
          prop: 'user',
          id: 4,
          order: 4,
          checked: true,
          width: 119,
        },
        {
          name: '通话号码',
          label: '通话号码',
          prop: 'phone',
          id: 5,
          order: 5,
          checked: true,
          width: 162,
        }, {
          name: '服务台',
          label: '服务台',
          prop: 'receptionToName',
          id: 6,
          order: 6,
          checked: true,
          width: 119,
        },
        {
          name: '所找人员',
          label: '所找人员',
          prop: 'findUserToName',
          id: 7,
          order: 7,
          checked: true,
          width: 119,
        },
        {
          name: '录音',
          label: '录音',
          prop: 'recording',
          id: 8,
          order: 8,
          checked: true,
        },
      ];
    },
    ticketTableColumn() {
      return [
        {
          name: '故障描述',
          label: '故障描述',
          prop: 'faultRemark',
          id: 10,
          order: 10,
          checked: true,
          width: 230,
          fixed: 'left',
        },
        {
          name: '紧急程度',
          label: '紧急程度',
          prop: 'degreeToName',
          id: 1,
          order: 1,
          checked: true,
          width: 119,
          fixed: false,
        }, {
          name: '状态',
          label: '状态',
          prop: 'currStateToName',
          id: 2,
          order: 2,
          checked: true,
          width: 102,
          fixed: false,
        }, {
          name: '影响范围',
          label: '影响范围',
          prop: 'rangeTypeToName',
          id: 3,
          order: 3,
          checked: true,
          width: 137,
          fixed: false,
        }, {
          name: '报修时间',
          label: '报修时间',
          prop: 'createTime',
          id: 5,
          order: 5,
          checked: true,
          width: 227,
          fixed: false,
        }, {
          name: '报修电话',
          label: '报修电话',
          prop: 'phone',
          id: 4,
          order: 4,
          checked: true,
          width: 140,
          fixed: false,
        }, {
          name: '报修科室',
          label: '报修科室',
          prop: 'deptName',
          id: 6,
          order: 6,
          checked: true,
          width: 124,
          fixed: false,
        }, {
          name: '工单来源',
          label: '工单来源',
          prop: 'sourceToName',
          id: 7,
          order: 7,
          checked: true,
          width: 120,
          fixed: false,
        }, {
          name: '建单人',
          label: '建单人',
          prop: 'createUserName',
          id: 8,
          order: 8,
          checked: true,
          width: 120,
          fixed: false,
        }, {
          name: '处理人',
          label: '处理人',
          prop: 'makeUserName',
          id: 9,
          order: 9,
          checked: true,
          width: 120,
          fixed: false,
        },
      ];
    },
  },
  async mounted() {
    this.$refs.pureTable.afterFetchData = this.afterFetchData;
    this.$store.state['TICKET_SERVICE_DESK'].ws = new PureWebsocket({
      url: `ws://192.168.2.26:8080/server/desk?token=${this.$store.state['APP_LOGIN'].accessToken}`,
    });
  },
  async created() {
    // this.columns = this.callRecordTableColumn;
    this.columns = this.ticketTableColumn;
  },
  methods: {
    onTemplateTypeChange(type) {
      // 属于通话记录的模板
      // 电话报修-phoneCreate
      // 已接-pickedUp
      // 未接-missed
      // 待建单-untenited
      // 电话找人-findSomeone 与普通通话记录表头不一样
      const callRecordTemplate = [
        'PHONE_CREATE',
        'PICKED_UP',
        'MISSED',
        'UNTENITED',
        'FIND_SOMEONE',
      ];
      this.$refs.pureTable.currentPage = 0;
      if (callRecordTemplate.includes(type)) {
        this.tableColumnType = 'callRecord';
        this.columns = this.callRecordTableColumn;
        this.listApi = ServiceDeskApi.callRecordList;
      } else {
        this.tableColumnType = 'ticket';
        this.columns = this.ticketTableColumn;
        this.listApi = ServiceDeskApi.list;
      }
      this.queryCondition.temp = type;
    },
    async afterFetchData() {
      const rs = await ServiceDeskApi.redInfo({ ...this.queryCondition, });
      this.redData = Object.assign({}, this.redData, rs);
      // TODO mock数据，正式需删除
      // this.$refs.pureTable.data = [
      //   {
      //     callType: 1,
      //     callTypeToName: '拨出',
      //     phone: '15196634454',
      //     deptName: '四川/成都',
      //     dealTypeToName: '创建工单',
      //     linkedCode: '5201314',
      //     recording: 'https://www.runoob.com/try/demo_source/horse.mp3',
      //     faultRemark: '这是个事故',
      //     hurryCount: 1000,
      //     repeatCount: 1000,
      //     orderNum: '9999',
      //   },
      //   {
      //     callType: 2,
      //     callTypeToName: '未接',
      //     phone: '15196634454',
      //     deptName: '四川/成都',
      //     dealTypeToName: '创建工单',
      //     linkedCode: '5201314',
      //     faultRemark: '这是个事故fjkdjfkdjfkdjkfjdkfjdkjfkdjffffffffffffffffffffffffffffffffffffffffffffffff',
      //     hurryCount: 1000,
      //     repeatCount: 1000,
      //     orderNum: '9999#',
      //     parentOrderNum: 'ss',
      //   },
      //   {
      //     callType: 0,
      //     callTypeToName: '已接',
      //     phone: '15196634454',
      //     deptName: '四川/成都',
      //     dealTypeToName: '创建工单',
      //     linkedCode: null,
      //     faultRemark: '这是个事故',
      //     hurryCount: 1000,
      //     repeatCount: 1000,
      //     orderNum: '9999',
      //   },
      // ];
    },
    onFlowChartPanelTransitionEnd() {
      setTimeout(() => {
        this.$refs.pureTable.setTableMaxHeight();
      }, 100);
    },
    onToggleQueryCondition() {
      this.queryConditionExpand = !this.queryConditionExpand;
      this.$nextTick(() => {
        this.$refs.pureTable.setTableMaxHeight();
      });
    },
    onQueryRecord() {
      this.queryCondition.keyword = this.queryConditionTemp.recordQuery;
      this.queryCondition.createInfoStartDate = this.queryConditionTemp.createInfoDate?.[0];
      this.queryCondition.createInfoEndDate = this.queryConditionTemp.createInfoDate?.[1];
      this.queryCondition.dealType = this.queryConditionTemp.dealType;
      this.queryCondition.userList = this.queryConditionTemp.userList;
      this.queryCondition.hospitalList = this.queryConditionTemp.hospitalList;
    },
    onResetRecord() {
      this.queryConditionTemp.recordQuery = null;
      this.queryConditionTemp.createInfoDate = [];
      this.queryConditionTemp.userList = [];
      this.queryConditionTemp.hospitalList = [];
      this.queryConditionTemp.dealType = null;
      this.onQueryRecord();
    },
    onQueryTicket() {
      this.queryCondition.keyword = this.queryConditionTemp.ticketQuery;
      this.queryCondition.createInfoStartDate = this.queryConditionTemp.ticketCreateInfoDate?.[0];
      this.queryCondition.createInfoEndDate = this.queryConditionTemp.ticketCreateInfoDate?.[1];
      this.queryCondition.createUserList = this.queryConditionTemp.createUserList;
      this.queryCondition.degree = this.queryConditionTemp.degree;
      this.queryCondition.rangeType = this.queryConditionTemp.rangeType;
      this.queryCondition.source = this.queryConditionTemp.source;
      this.queryCondition.orderState = this.queryConditionTemp.orderState;
      this.queryCondition.makeUserList = this.queryConditionTemp.makeUserList;
      this.queryCondition.serverUserList = this.queryConditionTemp.serverUserList;
      this.queryCondition.hospitalList = this.queryConditionTemp.ticketHospitalList;
    },
    onResetTicket() {
      this.queryConditionTemp.ticketQuery = null;
      this.queryConditionTemp.ticketCreateInfoDate = [];
      this.queryConditionTemp.createUserList = [];
      this.queryConditionTemp.degree = null;
      this.queryConditionTemp.rangeType = null;
      this.queryConditionTemp.source = null;
      this.queryConditionTemp.orderState = null;
      this.queryConditionTemp.makeUserList = [];
      this.queryConditionTemp.serverUserList = [];
      this.queryConditionTemp.ticketHospitalList = [];
      this.onQueryTicket();
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/common/styles/theme/handle.scss";
@import "../common/ticket.scss";
.pure {
padding: 0px !important;
.header {
  @include background_color_imp('color-bg');
  height: auto !important;
}
.el-main {
  padding: 16px;
}
.agent {
  font-size: 14px;
  @include font_color_imp('color-text-minor');
  &-value {
    @include font_color_imp('color-primary');
  }
}
.service-desk {
  @include background_color_imp('color-assist-4');
  padding: 6px;
}
.item {
  width: 240px;
  margin-right: 16px;
  margin-bottom: 16px;
}
.service-detail {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  @include font_color_imp('color-primary');
  font-size: 14px;
  .item {
    text-align: center;
    width: 108px;
    display: inline-block;
    margin: 0;
    @include font_color_imp('color-text-minor');
    span {
      @include font_color_imp('color-primary')
    }
  }
}
}

</style>
